﻿using Xejen.Database.Dapper;
using Xejen.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Xejen.Framework.Database.Dapper.Sqlite.Test
{
    public partial class MainForm : Form
    {
        private readonly IRepository<DataTransferRecordEntity, long> _dataTransferRecordRepository;
        private readonly IRepository<ApiRequestRecordEntity, long> _apiRequestRecordRepository;
        private readonly IAppHost _appHost;
        private readonly AsyncLock dbContextLock = new AsyncLock();
        private readonly IUnitOfWork _unitOfWork;
        private readonly IServiceProvider _serviceProvider;

        public MainForm(
            IAppHost appHost,
            IUnitOfWork unitOfWork,
            IRepository<DataTransferRecordEntity, long> dataTransferRecordRepository,
            IRepository<ApiRequestRecordEntity, long> apiRequestRecordRepository,
            IServiceProvider serviceProvider)
        {
            _appHost = appHost;
            _unitOfWork = unitOfWork;
            _dataTransferRecordRepository = dataTransferRecordRepository;
            _apiRequestRecordRepository = apiRequestRecordRepository;
            _serviceProvider = serviceProvider;

            InitializeComponent();
        }

        /// <summary>
        /// 增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button1_Click(object sender, EventArgs e)
        {
            var entity1 = _apiRequestRecordRepository.Insert("INSERT INTO ApiRequestRecords (Name, RequestAddress,CreationTime) VALUES (@Name, @RequestAddress,@CreationTime);", new ApiRequestRecordEntity
            {
                Name = "Test",
                RequestAddress = "address",
                CreationTime = StandardTime.Now,
            });

            var entity2 = await _apiRequestRecordRepository.InsertAndGetIdAsync("INSERT INTO ApiRequestRecords (Name, RequestAddress,CreationTime) VALUES (@Name, @RequestAddress,@CreationTime);", new ApiRequestRecordEntity
            {
                Name = "Test2",
                RequestAddress = "address2",
                CreationTime = StandardTime.Now,
            });

            //批量插入
            var entity3 = await _apiRequestRecordRepository.InsertAsync("INSERT INTO ApiRequestRecords (Name, RequestAddress,CreationTime) VALUES (@Name, @RequestAddress,@CreationTime);",
                new List<ApiRequestRecordEntity> {
                    new ApiRequestRecordEntity  {
                        Name = "Test3",
                        RequestAddress = "address3",
                        CreationTime = StandardTime.Now,
                    },
                    new ApiRequestRecordEntity  {
                        Name = "Test4",
                        RequestAddress = "address4",
                        CreationTime = StandardTime.Now,
                    },
                });

            //释放DbContext的写法，此写法，要求IDbContextProvider在依赖注入的时候，使用AddTransient方式
            var provider = _serviceProvider.GetService<IDbContextProvider<SQLiteConnection>>();
            using (var repository = new DapperRepository<SQLiteConnection, ApiRequestRecordEntity, long>(provider))
            {
                repository.Insert("INSERT INTO ApiRequestRecords (Name, RequestAddress,CreationTime) VALUES (@Name, @RequestAddress,@CreationTime);", new ApiRequestRecordEntity
                {
                    Name = "马志远",
                    RequestAddress = "测试地址",
                    CreationTime = StandardTime.Now,
                });
            }
        }
        /// <summary>
        /// 循环增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            Task.Run(async () =>
            {
                while (true)
                {
                    try
                    {
                        _ = ExecuteAsync();
                    }
                    catch (System.Exception exp)
                    {
                        Debug.WriteLine("增的时候出错：\r\n" + exp);
                    }

                    await Task.Delay(1);
                }
            });
        }

        private async Task ExecuteAsync()
        {
            //Random random = new Random();
            //if (random.Next(1, 100) > 50)
            //{
            //    //var provider = _appHost.ServiceProvider.GetRequiredService<IDbContextProvider<TestSqlSugarDbContext>>();
            //    //var apiRequestRecordRepository = new SqlSugarRepository<TestSqlSugarDbContext, ApiRequestRecordEntity, long>(provider);

            //    using (await dbContextLock.LockAsync())
            //    {
            //        var insertEntity = await _apiRequestRecordRepository.InsertAsync(new ApiRequestRecordEntity
            //        {
            //            ReceiveData = "收到的数据",
            //            SendData = "发送的数据",
            //            Msg = "错误信息",
            //            ReturnCode = "200",
            //            Name = "Api名称",
            //            RequestAddress = "http://baidu.com"
            //        });
            //        Debug.WriteLine($"刚插入的实体类的所产生的主键ID是：{insertEntity.Id}");
            //    }
            //}
        }

        /// <summary>
        /// 删
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button2_Click(object sender, EventArgs e)
        {
            _apiRequestRecordRepository.Delete("delete from ApiRequestRecords where Id=@Id", 1);
            await _apiRequestRecordRepository.DeleteAsync("delete from ApiRequestRecords where Id=@Id", new ApiRequestRecordEntity { Id = 2 });
            //批量删除
            _apiRequestRecordRepository.Delete("delete from ApiRequestRecords where Id=@Id",
                new List<ApiRequestRecordEntity> {
                    new ApiRequestRecordEntity { Id = 5, },
                    new ApiRequestRecordEntity { Id = 6, }
                });
        }

        /// <summary>
        /// 改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button3_Click(object sender, EventArgs e)
        {
            var entity3 = _apiRequestRecordRepository.Update("UPDATE ApiRequestRecords SET Name = @Name WHERE Id = @Id", new ApiRequestRecordEntity { Id = 3, Name = "测试3" });
            var entity4 = await _apiRequestRecordRepository.UpdateAsync("UPDATE ApiRequestRecords SET Name = @Name WHERE Id = @Id", new ApiRequestRecordEntity { Id = 4, Name = "测试4" });
            //批量更新
            var entity5 = await _apiRequestRecordRepository.UpdateAsync("UPDATE ApiRequestRecords SET Name = @Name WHERE Id = @Id", new List<ApiRequestRecordEntity> {
                new ApiRequestRecordEntity { Id = 7, Name = "测试7" },
                new ApiRequestRecordEntity { Id = 8, Name = "测试8" },
            });
        }

        /// <summary>
        /// 查
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button4_Click(object sender, EventArgs e)
        {
            var entity1 = _apiRequestRecordRepository.GetAll("select * from ApiRequestRecords where id=1;").ToList();
            var entity2 = _apiRequestRecordRepository.Single("select * from ApiRequestRecords where id=1;");
            var entity3 = _apiRequestRecordRepository.SingleOrDefault("select * from ApiRequestRecords where id=9999999;");
            var entity4 = _apiRequestRecordRepository.FirstOrDefault("select * from ApiRequestRecords where id=1;");
            var entity5 = await _apiRequestRecordRepository.FirstOrDefaultAsync("select * from ApiRequestRecords where id=1;");
            var entity6 = (await _apiRequestRecordRepository.GetAllAsync("select * from ApiRequestRecords;")).ToList();
            var entity7 = await _apiRequestRecordRepository.GetAllListAsync("select * from ApiRequestRecords;");
        }

        /// <summary>
        /// 循环查
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
            //Task.Run(async () =>
            //{
            //    while (true)
            //    {
            //        try
            //        {
            //            using (await dbContextLock.LockAsync())
            //            {
            //                var count = _apiRequestRecordRepository.GetAll().OrderByDescending(q => q.CreationTime).Where(q => q.CreationTime >= DateTime.Now.AddDays(-1)).Count();
            //                Debug.WriteLine($"数量：{count}");
            //            };
            //        }
            //        catch (System.Exception exp)
            //        {
            //            Debug.WriteLine("查的时候出错：\r\n" + exp);
            //        }
            //        await Task.Delay(10);
            //    }
            //});
        }

        /// <summary>
        /// 事务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button7_Click(object sender, EventArgs e)
        {
            //using (var context = ((IRepositoryWithDbContext)_requestLogRepository).GetDbContext())
            //{
            //    try
            //    {
            //        context.BeginTran();
            //        var result = await _requestLogRepository.InsertAsync(new DataTransferRecordEntity
            //        {
            //            ErrorMessage = "错误消息",
            //            CreationTime = StandardTime.Now,
            //            DurationTotalMilliseconds = 100,
            //            RecordType = 2,
            //            HandleStatus = 1,
            //            Data = "json数据包",
            //            StartTime = StandardTime.Now.AddSeconds(-2),
            //            EndTime = StandardTime.Now,
            //            Summary = "测试一下林黛玉",
            //        });

            //        var entity = await _requestLogRepository.FirstOrDefaultAsync(q => q.Id == 9999);
            //        if (entity == null)
            //        {
            //            Debug.WriteLine("无数据，无法演示修改");
            //            context.RollbackTran();
            //            return;
            //        }
            //        entity.ErrorMessage = "林黛玉事务失败了";
            //        await _requestLogRepository.UpdateAsync(entity);

            //        context.CommitTran();
            //    }
            //    catch (Exception ex)
            //    {
            //        context.RollbackTran();
            //        Debug.WriteLine("发生错误: " + ex.Message);
            //    }
            //}
        }

        private async void button8_Click(object sender, EventArgs e)
        {
            try
            {
                _unitOfWork.BeginTransaction();

                var result = await _apiRequestRecordRepository.InsertAsync("INSERT INTO ApiRequestRecords (Name, RequestAddress,CreationTime) VALUES (@Name, @RequestAddress,@CreationTime);",
                    new ApiRequestRecordEntity
                    {
                        CreationTime = StandardTime.Now,
                        SendData = "json数据包",
                        ReceiveData = "收到的数据",
                        ReturnCode = "Success",
                        Name = "另魂牵梦萦魂牵梦萦你用",
                    });

                var entity = await _apiRequestRecordRepository.FirstOrDefaultAsync("select * from ApiRequestRecords where id=9999999;");
                if (entity == null)
                {
                    Debug.WriteLine("无数据，无法演示修改");
                    _unitOfWork.Rollback();
                    return;
                }
                entity.Msg = "林黛玉事务失败了";
                await _apiRequestRecordRepository.UpdateAsync("UPDATE ApiRequestRecords SET Msg = @Msg WHERE Id = @Id", entity);

                _unitOfWork.Commit();
            }
            catch (Exception ex)
            {
                _unitOfWork.Rollback();
                Debug.WriteLine("发生错误: " + ex.Message);
            }
        }
    }
}
